package com.standardoperationapp.net;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


import com.standardoperationapp.activity.LoginActivity;

import org.json.JSONObject;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import io.reactivex.observers.DisposableObserver;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

//用于在Http请求开始时，自动显示一个ProgressDialog
//在Http请求结束是，关闭ProgressDialog
//调用者自己对请求数据进行处理   成功时 通过result是否等于1分别回调onSuccess和onFault，默认处理了401错误转登录。
//回调结果为String，需要手动序列化

public class OnSuccessAndFaultSub extends DisposableObserver<ResponseBody>
        implements ProgressCancelListener {
    //是否需要显示默认Loading
    private boolean showProgress = true;
    private OnSuccessAndFaultListener mOnSuccessAndFaultListener;

    private Context context;
    private ProgressDialog progressDialog;


    //mOnSuccessAndFaultListener 成功回调监听
    public OnSuccessAndFaultSub(OnSuccessAndFaultListener mOnSuccessAndFaultListener) {
        this.mOnSuccessAndFaultListener = mOnSuccessAndFaultListener;
    }


    //mOnSuccessAndFaultListener 成功回调监听
    public OnSuccessAndFaultSub(OnSuccessAndFaultListener mOnSuccessAndFaultListener, Context context) {
        this.mOnSuccessAndFaultListener = mOnSuccessAndFaultListener;
        this.context = context;
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在加载中请稍后~");
    }


    //@param mOnSuccessAndFaultListener 成功回调监听
    // * @param context 上下文
    //* @param showProgress 是否需要显示默认Loading
    public OnSuccessAndFaultSub(OnSuccessAndFaultListener mOnSuccessAndFaultListener, Context context, boolean showProgress) {
        this.mOnSuccessAndFaultListener = mOnSuccessAndFaultListener;
        this.context = context;
        progressDialog = new ProgressDialog(context);
        this.showProgress = showProgress;
    }


    private void showProgressDialog() {
        if (showProgress && null != progressDialog) {
            progressDialog.show();
        }
    }


    private void dismissProgressDialog() {
        if (showProgress && null != progressDialog) {
            progressDialog.dismiss();
        }
    }


    //* 订阅开始时调用
    //* 显示ProgressDialog
    @Override
    public void onStart() {
        showProgressDialog();
    }


    //完成，隐藏ProgressDialog
    @Override
    public void onComplete() {
        dismissProgressDialog();
        progressDialog = null;
    }


    //对错误进行统一处理
    // 隐藏ProgressDialog
    @Override
    public void onError(Throwable e) {
        try {
            if (e instanceof SocketTimeoutException) {//请求超时
            } else if (e instanceof ConnectException) {//网络连接超时
                mOnSuccessAndFaultListener.onFault("网络连接超时");
            } else if (e instanceof SSLHandshakeException) {//安全证书异常
                mOnSuccessAndFaultListener.onFault("安全证书异常");
            } else if (e instanceof HttpException) {//请求的地址不存在
                int code = ((HttpException) e).code();

                if(code == 1 || code == 500){
                    String msg = ((HttpException) e).response().errorBody().string();
                    JSONObject jsonObject = new JSONObject(msg);
                    String str = (String) jsonObject.get("msg");
                    if(null == str){
                        mOnSuccessAndFaultListener.onFault("请求出错");
                    }else{
                        Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    }
                }else if(code == 401){
                    String msg = ((HttpException) e).response().errorBody().string();
                    JSONObject jsonObject = new JSONObject(msg);
                    String str = (String) jsonObject.get("msg");
                    if(!"error".equals(str)){
                        Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    }
                }else if(code == 424){
                    String msg = ((HttpException) e).response().errorBody().string();
                    JSONObject jsonObject = new JSONObject(msg);
                    String str = (String) jsonObject.get("msg");
                    if(!"error".equals(str)){
                        Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    }
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);
                }else  if (code == 504) {
                    mOnSuccessAndFaultListener.onFault("网络异常，请检查您的网络状态");
                } else if (code == 404) {
                    mOnSuccessAndFaultListener.onFault("请求的地址不存在");
                } else {
                    String msg = ((HttpException) e).response().errorBody().string();
                    JSONObject jsonObject = new JSONObject(msg);
                    String str = (String) jsonObject.get("msg");
                    if(!"error".equals(str)){
                        Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    }
                    mOnSuccessAndFaultListener.onFault("请求失败");
                }
            } else if (e instanceof UnknownHostException) {//域名解析失败
                mOnSuccessAndFaultListener.onFault("域名解析失败");
            } else {
                mOnSuccessAndFaultListener.onFault("error:" + e.getMessage());
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            if(!TextUtils.isEmpty(e.getMessage())){
                Log.e("OnSuccessAndFaultSub", "error:" + e.getMessage());
            }
            dismissProgressDialog();
            progressDialog = null;

        }

    }


    //* 当result等于1回调给调用者，否则自动显示错误信息，若错误信息为401跳转登录页面。
    //        * ResponseBody  body = response.body();//获取响应体
    // * InputStream inputStream = body.byteStream();//获取输入流
    // * byte[] bytes = body.bytes();//获取字节数组
    // * String str = body.string();//获取字符串数据
    @Override
    public void onNext(ResponseBody body) {
        try {

            JSONObject jsonObject = new JSONObject(body.string());
            int resultCode = jsonObject.getInt("code");
            if(resultCode == 1){
                Intent intent = new Intent(context, LoginActivity.class);
                context.startActivity(intent);
            }
            if (resultCode == 200 || resultCode == 0) {
               Log.d("zczw:OnSuccessAndbody-----", jsonObject.toString());
                mOnSuccessAndFaultListener.onSuccess(jsonObject);
            } else {
                String errorMsg = jsonObject.getString("msg");
                mOnSuccessAndFaultListener.onFault(errorMsg);
                if(!"error".equals(errorMsg)){
                    Toast.makeText(context, "code:"+resultCode + ",msg:" + errorMsg, Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //取消ProgressDialog的时候，取消对observable的订阅，同时也取消了http请求
    @Override
    public void onCancelProgress() {
        if (!this.isDisposed()) {
            this.dispose();
        }
    }
}
